const { fstat } = require('fs');
const mfs = require('./mfs');
const utils = require('./utils');
function pack(config) {


    // 可以读取文件后，进行正则表达式，修改需要的内容
    // const data = mfs.readFile(mfs.join(config.appPath, 'build.gradle'), { encoding: 'utf-8' });
    // console.log('data', data);
    const projGradle =
        'buildscript {\n' +
        '    repositories {\n' +
        '        google()\n' +
        '        jcenter()\n' +
        '    }\n' +
        '    dependencies {\n' +
        '        classpath \'com.android.tools.build:gradle:3.2.0\'\n' +
        // 如果没有集成buglly，则不要
        '        classpath \'com.tencent.bugly:symtabfileuploader:2.2.1\'\n' +
        '    }\n' +
        '}\n' +
        'allprojects {\n' +
        '    repositories {\n' +
        '        google()\n' +
        '        jcenter()\n' +
        '        flatDir {\n' +
        '            dirs \'libs\'\n' +
        '        }\n' +
        '        maven {\n' +
        '            url \"http://localhost:8081/repository/maven-public/\"\n' +
        '        }\n' +
        '    }\n' +
        '}\n' +
        'task clean(type: Delete) {\n' +
        '    delete rootProject.buildDir\n' +
        '}\n';
    mfs.writeFile(mfs.join(config.androidPath, 'build.gradle'), projGradle);

    // 因为我们在多渠道中定义了应用名，避免重复，这里先临时暴力删除
    const stringValuePath = mfs.join(config.androidPath, 'res', 'values', 'strings.xml');
    mfs.rm(stringValuePath);

    // 修改较多，重写
    let appPath = mfs.join(config.androidPath, 'app');
    let abiFilters = 'abiFilters ';
    for (let i = 0; i < config.appABIs.length; i++) {
        abiFilters += '\'' + config.appABIs[i] + '\'';
        if (i != config.appABIs.length - 1) {
            abiFilters += ',';
        }
    }

    let channel = '';
    for (let i = 0; i < config.channel.length; i++) {
        const name = config.channel[i];
        let py = utils.getFirstLetter(name);
        channel += py + '{\n' +
            '            dimension \"channel\"\n' +
            '            manifestPlaceholders = [\n' +
            '                APP_CHANNEL:\"' + name + '\"\n' +
            '            ]\n' +
            '        }\n'
    }

    const data =
        'import org.apache.tools.ant.taskdefs.condition.Os\n' +
        'apply plugin: \'com.android.application\'\n' +
        // 集成bugly start
        'apply plugin: \'bugly\'\n' +
        'bugly {\n' +
        '    appId = \'' + config.buglyAppId + '\'\n' +
        '    appKey = \'' + config.buglyAppKey + '\'\n' +
        '}\n' +
        // 集成bugly 结束
        'android {\n' +
        '    compileSdkVersion ' + config.apiLevel + '\n' +
        '    buildToolsVersion \"' + config.buildToolsVersion + '\"\n' +
        '    defaultConfig {\n' +
        // 指定了多维度多渠道，此处的包名在下面指定
        // 'applicationId \"' + config.packageName + '\"\n' +
        '        minSdkVersion 19\n' +
        '        targetSdkVersion ' + config.apiLevel + '\n' +
        '        versionCode ' + config.appCode + '\n' +
        '        versionName \"' + config.appVer + '\"\n' +
        '        multiDexEnabled true\n' +
        // 指定多维度
        '        flavorDimensions \"app\",\"channel\"\n' +
        '        ndk {\n' +
        '            ' + abiFilters + '\n' +
        '        }\n' +
        '        externalNativeBuild {\n' +
        '            ndkBuild {\n' +
        '                if (!project.hasProperty("PROP_NDK_MODE") || PROP_NDK_MODE.compareTo(\'none\') != 0) {\n' +
        '                    targets \'cocos2djs\'\n' +
        '                    arguments \'NDK_TOOLCHAIN_VERSION=clang\'\n' +
        '                    def module_paths = [project.file(\"' + config.enginePath + '/resources/cocos2d-x\"),\n' +
        '                                        project.file(\"' + config.enginePath + '/resources/cocos2d-x/cocos\"),\n' +
        '                                        project.file(\"' + config.enginePath + '/resources/cocos2d-x/external\")]\n' +
        '                    if (Os.isFamily(Os.FAMILY_WINDOWS)) {\n' +
        '                        arguments \'NDK_MODULE_PATH=\' + module_paths.join(\";\")\n' +
        '                    } else {\n' +
        '                        arguments \'NDK_MODULE_PATH=\' + module_paths.join(\':\')\n' +
        '                    }\n' +
        '                    arguments \'-j\' + Runtime.runtime.availableProcessors()\n' +
        '                    abiFilters.addAll(PROP_APP_ABI.split(\':\').collect{ it as String })\n' +
        '                }\n' +
        '            }\n' +
        '        }\n' +
        '    }\n' +
        // 维度
        '    productFlavors {\n' +
        // APP维度
        '        ' + config.title + '{\n' +
        '            dimension \"app\"\n' +
        // 包名
        '            applicationId \"' + config.packageName + '\"\n' +
        // 应用名
        '            resValue \"string\", \"app_name\",\"' + config.appName + '\"\n' +
        '            manifestPlaceholders = [\n' +
        '                APP_ID:\"' + config.appId + '\",\n' +
        '                APP_SECRET:\"' + config.appKey + '\",\n' +
        '                ORIENTATION:\"' + config.orientation + '\"\n' +
        '            ]\n' +
        '        }\n' +
        // 渠道维度
        '       ' + channel +
        '    }\n' +
        '    sourceSets.main {\n' +
        '        java.srcDirs \"../src\", \'src\'\n' +
        '        res.srcDirs \"../res\", \'res\'\n' +
        '        jniLibs.srcDirs \"../libs\", \'libs\'\n' +
        '        manifest.srcFile \"AndroidManifest.xml\"\n' +
        '    }\n' +
        '    externalNativeBuild {\n' +
        '        ndkBuild {\n' +
        '            if (!project.hasProperty(\"PROP_NDK_MODE\") || PROP_NDK_MODE.compareTo(\'none\') != 0) {\n' +
        '                path \"jni/Android.mk\"\n' +
        '            }\n' +
        '        }\n' +
        '    }\n' +
        // 签名
        '    signingConfigs {\n' +
        '        release {\n' +
        '            storeFile file(\"' + config.storeFile.replace(/\\/g, '/') + '\")\n' +
        '            storePassword \"' + config.storePassword + '\"\n' +
        '            keyAlias \"' + config.keyAlias + '\"\n' +
        '            keyPassword \"' + config.keyPassword + '\"\n' +
        '        }\n' +
        '    }\n' +
        '    buildTypes {\n' +
        '        release {\n' +
        '            debuggable false\n' +
        '            jniDebuggable false\n' +
        '            renderscriptDebuggable false\n' +
        '            minifyEnabled true\n' +
        '            shrinkResources true\n' +
        '            proguardFiles getDefaultProguardFile(\'proguard-android.txt\'), \'proguard-rules.pro\'\n' +
        '            if (project.hasProperty(\"RELEASE_STORE_FILE\")) {\n' +
        '                signingConfig signingConfigs.release\n' +
        '            }\n' +
        '            externalNativeBuild {\n' +
        '                 ndkBuild {\n' +
        '                     arguments \'NDK_DEBUG=0\'\n' +
        '                 }\n' +
        '            }\n' +
        '        }\n' +
        '        debug {\n' +
        '            debuggable true\n' +
        '            jniDebuggable true\n' +
        '            renderscriptDebuggable true\n' +
        '            externalNativeBuild {\n' +
        '                ndkBuild {\n' +
        '                    arguments \'NDK_DEBUG=1\'\n' +
        '                }\n' +
        '            }\n' +
        '        }\n' +
        '    }\n' +
        '}\n' +
        'android.applicationVariants.all {\n' +
        '    variant ->\n' +
        // 'delete \"${buildDir}/intermediates/merged_assets/${variant.dirName}\"\n' +
        // 因为修改成了多渠道打包，这样子无法直接删除缓存，需要删除整个目录
        '        delete \"${buildDir}/intermediates/merged_assets/\"\n' +
        '        variant.mergeAssets.doLast {\n' +
        '            def sourceDir = \"${buildDir}/../../../../..\"\n' +
        '            copy {\n' +
        '                from \"${sourceDir}/res\"\n' +
        '                into \"${outputDir}/res\"\n' +
        '            }\n' +
        '            copy {\n' +
        '                from \"${sourceDir}/subpackages\"\n' +
        '                into \"${outputDir}/subpackages\"\n' +
        '            }\n' +
        '            copy {\n' +
        '                from \"${sourceDir}/src\"\n' +
        '                into \"${outputDir}/src\"\n' +
        '            }\n' +
        '            copy {\n' +
        '                from \"${sourceDir}/jsb-adapter\"\n' +
        '                into \"${outputDir}/jsb-adapter\"\n' +
        '            }\n' +
        '            copy {\n' +
        '                from \"${sourceDir}/main.js\"\n' +
        '                from \"${sourceDir}/project.json\"\n' +
        '                into outputDir\n' +
        '            }\n' +
        '        }\n' +
        // 重命名打包后的名字和路径
        '        variant.outputs.all {\n' +
        '            variant.getPackageApplication().outputDirectory = new File(\"' + config.outDir.replace(/\\/g, '/') + '/${variant.productFlavors[0].name}/${variant.productFlavors[1].name}\")\n' +
        '            def date = new Date().format(\"yyyyMMddHHmm\")\n' +
        '            outputFileName = \"${variant.productFlavors[0].name}_${variant.productFlavors[1].name}_${versionName}_${versionCode}_${date}.apk\"\n' +
        '        }\n' +
        '}\n' +
        'dependencies {\n' +
        '    implementation fileTree(dir: \'libs\', include: [\'*.jar\', \'*.aar\'])\n' +
        '    implementation fileTree(dir: \"' + config.enginePath + '/resources/cocos2d-x/cocos/platform/android/java/libs\", include: [\'*.jar\'])\n' +
        '    implementation project(\':libcocos2dx\')\n' +
        '}\n';


    mfs.writeFile(mfs.join(appPath, 'build.gradle'), data);

    return new Promise((resolve, reject) => {
        utils.execFile('gradlew.bat', [':' + config.title + ':assembleRelease'], { cwd: config.androidPath }, (error, stdout, stderr) => {
            if (error) {
                console.log('error', error);
                reject();
            } else {
                console.log('执行成功');
                resolve();
            }
        });
    });
}

module.exports.pack = pack;